/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gameheartv2;

import java.net.*;
import java.io.*;
import java.util.ArrayList;

public class Client implements Runnable {

    private int first = 1;
    private Socket socket = null;
    private Thread thread = null;
    private DataInputStream console = null;
    private DataOutputStream streamOut = null;
    private ClientThread client = null;
    public static GameStateTableCard tableCard;
    public int num = -1;
    public int type = -1;
    public String[] baiDuocChia = new String[13];
    public int[] baichia = new int[27];
    public int soTran = 1;
    int Cardcount = 0;
    public int currentPlayer = -1;
    public int startPlayer = -1;

    public Client(String serverName, int serverPort) {
        System.out.println("Establishing connection. Please wait ...");
        try {
            socket = new Socket(serverName, serverPort);

            System.out.println("Connected: " + socket);
            start();
        } catch (UnknownHostException uhe) {
            System.out.println("Host unknown: " + uhe.getMessage());
        } catch (IOException ioe) {
            System.out.println("Unexpected exception: " + ioe.getMessage());
        }
    }

    public void run() {
        while (thread != null) {
            try {

                streamOut.writeUTF(console.readLine());
                streamOut.flush();
            } catch (IOException ioe) {
                System.out.println("Sending error: " + ioe.getMessage());
                stop();
            }
        }
    }

    public void send(String msg) {

        try {
            streamOut.writeUTF(msg);
            streamOut.flush();
        } catch (IOException ioe) {
            System.out.println("Sending error: " + ioe.getMessage());
            stop();
        }

    }

    public void handle(String msg) {
//        if (msg.equals(".bye")) {
//            System.out.println("Good bye. Press RETURN to exit ...");
//            stop();
//        } else {
//            if(msg.equals("1"))
//            {
//            GameStateTableCard.vCard.elementAt(0).setBounds(400,340,57,74);
//            tableCard.mainGame.getLayeredPane().setLayer(GameStateTableCard.vCard.elementAt(0),tableCard.topCard);
//            tableCard.topCard++;
//            }
// else
//            {
//            GameStateTableCard.vCard.elementAt(2).setBounds(400,340,57,74);
//            tableCard.mainGame.getLayeredPane().setLayer(GameStateTableCard.vCard.elementAt(0),tableCard.topCard);
//            tableCard.topCard++;
// }
//
//        }
        System.out.print("sent message" + msg);
        String[] parameterArray = msg.split(" ");
        int code = Integer.parseInt(parameterArray[0]);
        String sentMsg;
        switch (code) {
            case 4:
                int result = Integer.parseInt(parameterArray[1]);
                if (1 == result) {
                    Client.tableCard.viTri = Integer.parseInt(parameterArray[2]);
                    GameStateRoom.ChangeState(GameDef.STATE_TABLECARD);
                    if (Client.tableCard.viTri == 4) {
                        GameStateTableCard.client.send("5");
                    }
                } else {
                    System.out.print("khong ket noi duoc");
                }
                break;
            case 6:
                System.out.println(msg);
                startPlayer = Integer.parseInt(parameterArray[1]);

                for (int i = 1; i < 14; i++) {
                    this.baichia[Cardcount] = Integer.parseInt(parameterArray[i * 2]);
                    this.baiDuocChia[Cardcount / 2] = parameterArray[i * 2] + " " + parameterArray[i * 2 + 1];;
                    this.baichia[Cardcount + 1] = Integer.parseInt(parameterArray[i * 2 + 1]);
                    Cardcount = Cardcount + 2;
                }

                ArrayList ar = new ArrayList();
                for (int type = 0; type < 4; ++type) {
                    for (int i = 0; i < 13; i++) {
                        if (baichia[i * 2 + 1] == type) {
                            ar.add(baichia[i * 2]);
                            ar.add(baichia[i * 2 + 1]);
                        }
                    }
                }

                if (26 == this.Cardcount) {
                    for (int i = 12; i >= 0; --i) {
                        Object ob = ar.get(i * 2);
                        int num = Integer.valueOf(ob.toString().trim());
                        ob = ar.get(i * 2 + 1);
                        int type = Integer.valueOf(ob.toString().trim());

                        tableCard.vCard.elementAt(num + type * 13).isUse = true;
                    }
                    GameStateTableCard.trangThai = 4;
                }
                break;
            case 25:
                int nump = Integer.parseInt(parameterArray[1]);
                GameStateTableCard.vTablePlayer.clear();
                for (int i = 0; i < nump; i++) {
                    String name = parameterArray[2 + i * 2];
                    String path = parameterArray[3 + i * 2];
                    int vitri = i - (tableCard.viTri - 2);
                    if (vitri <= 0) {
                        vitri += 4;
                    }
                    Player player = new Player(name, path, 0, i, vitri);
                    GameStateTableCard.vTablePlayer.add(player);
                }
                break;


            case 16:
                for (int i = 2; i < 8; i++) {
                    //Card temp=tableCard.selectedCards.elementAt(i/2-1);
                    int number = Integer.parseInt(parameterArray[i]);
                    if (number == 13) {
                        number = 1;
                    }
                    int type = Integer.parseInt(parameterArray[i + 1]);
                    type = type - 1;
                    i++;
                    tableCard.selectedCards.elementAt(i / 2 - 1).isUse = false;
                    tableCard.vCard.elementAt(number + type * 13).isUse = true;
                    GameStateTableCard.trangThai = 2;
                    //tableCard.vCard.elementAt(number+type*13).setBounds(temp.getX(),temp.getY(),57,74);
                    //tableCard.mainGame.getLayeredPane().add(tableCard.vCard.elementAt(number+type*13),temp.layer);
                    //temp.setVisible(false);
                    //// GameStateRoom.ChangeState(GameDef.STATE_TABLECARD);
                }
                break;
            case 8:
                System.out.println("receive :   " + msg);
                num = Integer.parseInt(parameterArray[1]);
                type = Integer.parseInt(parameterArray[2]);
                
                currentPlayer = Integer.parseInt(parameterArray[4]);
                
                int position = num - 1 + (type - 1) * 13;
                int player = Integer.parseInt(parameterArray[3]);
                player = (4 + player - this.tableCard.viTri + 1) % 4;
                if (0 == player) {
                    player = 4;
                }
                int x = 400;
                int y = 340;
                if (1 == player) {
                    x = 400;
                    y = 340;
                }
                if (2 == player) {
                    x = 450;
                    y = 290;
                }
                if (3 == player) {
                    x = 400;
                    y = 240;
                }
                if (4 == player) {
                    x = 350;
                    y = 290;
                }
                GameStateTableCard.vCard.elementAt(position).setBounds(x, y, 57, 74);
                tableCard.mainGame.getLayeredPane().setLayer(GameStateTableCard.vCard.elementAt(position), tableCard.topCard);
                tableCard.topCard++;
                break;
            case 12:
                String name = parameterArray[1];
                String receivedMessage = "";
                for (int i = 2; i < parameterArray.length; i++) {
                    receivedMessage += parameterArray[i] + " ";
                }
                GameStateTableCard.tfShowMessage.append(name + ": " + receivedMessage + "\n");
                GameStateTableCard.tfShowMessage.setCaretPosition(GameStateTableCard.tfShowMessage.getText().length());
                break;
        }
    }

    public void start() throws IOException {
        console = new DataInputStream(System.in);
        streamOut = new DataOutputStream(socket.getOutputStream());
        if (thread == null) {
            client = new ClientThread(this, socket);
            thread = new Thread(this);
            thread.start();
        }
    }

    public void stop() {
        if (thread != null) {
            thread.stop();
            thread = null;
        }
        try {
            if (console != null) {
                console.close();
            }
            if (streamOut != null) {
                streamOut.close();
            }
            if (socket != null) {
                socket.close();
            }
        } catch (IOException ioe) {
            System.out.println("Error closing ...");
        }
        client.close();
        client.stop();
    }

    public static void main(String args[]) {
        Client client = null;

        client = new Client("192.168.183.1", 8999);

    }
}